package cn.gistone.visualeditor.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 文件上传工具
 */
public class FileUploadUtils {
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");


    public static String uploadFile(MultipartFile file, String path) throws Exception {
        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream bos = null;
        String url = null;
        try {
            url = targetFile+File.separator + LocalDateTime.now().format(dtf)+ file.getOriginalFilename();
            bos = new FileOutputStream(url);//FileOutputStream读取流的时候如果是文件夹，就会出错，无论怎么读，都拒绝访问，应该在读取的目录后面加上文件名
            bos.write(file.getBytes()); //前端文件传过来后端将文件通过流写入文件夹中
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            bos.flush();
            bos.close();
        }
        return url;
    }
}
